// 文件重命名
// 云端上传
/*
 * 配置保存:
   exports.data = {}
 * gui.App.dataPath + "/app.js"
 * gui.App.dataPath + "/recents.js"
   {
      recents: [{name, id, imageDir}]
   }
 * imageDir + "/data.js"
   {
      fileMap: {pointId: {reason, audit, path}},
      creator, //作者
      createtime,   //创建时间
      modifytime,   //最近修改时间
      name,   //车型名称
      id      //车型id
   }
 */

var fs = require('fs');
var pathUtil = require('path');
var http = require('http');
// 使用 Node.js 内置的 fs.mkdirSync 替代 mkdirp（支持 recursive 选项）
var mkdirp = {
    sync: function(dir) {
        try {
            fs.mkdirSync(dir, { recursive: true });
        } catch(e) {
            // 如果目录已存在，忽略错误
            if (e.code !== 'EEXIST') {
                throw e;
            }
        }
    }
};
// 延迟获取 bowlder，因为它在模块加载时可能还未定义
function getBowlder() {
    return window.bowlder;
}

// 延迟注册事件监听器，确保 bowlder 已加载
function registerEventHandlers() {
    var $$ = getBowlder();
    if (!$$) {
        // 如果 bowlder 还未加载，延迟重试
        setTimeout(registerEventHandlers, 50);
        return;
    }
    
    $$.on("point.audit", function(id, audit, reason){ //保存fileMap[id]
        var vehicleData = window.vehicleData;
        var gInfo = window.gInfo;
        if(!vehicleData.fileMap[id]){
            console.log(id + ' not found in vehicleData.fileMap.');
            return;
        }
        vehicleData.fileMap[id].audit = audit;
        vehicleData.fileMap[id].reason = reason || '';
        if(gInfo.store){
            gInfo.store.saveVehicle(window.imageDir);
        }
    });

    $$.on("batch.audit", function(checks, audit, reason){
        var vehicleData = window.vehicleData;
        var gInfo = window.gInfo;
        $$.each(checks, function(id){
            if(!vehicleData.fileMap[id]) return;
            if(!fs.existsSync(vehicleData.fileMap[id].path)){
                delete vehicleData.fileMap[id];
                return;
            }
            vehicleData.fileMap[id].audit = audit;
            vehicleData.fileMap[id].reason = reason || '';
        });
        if(gInfo.store){
            gInfo.store.saveVehicle(window.imageDir);
        }
    });
}

// 立即尝试注册，如果 bowlder 未加载则延迟
registerEventHandlers();

var isDir = function(dir){
    return fs.existsSync(dir) && fs.statSync(dir).isDirectory();
}

// 统一归一化任意输入成当前操作系统可用的本地文件系统路径
// 支持以下输入形式：
// - file:/// 路径（macOS/Linux/Windows）
// - /C:/path 或 C:\path（Windows）
// - 普通相对/绝对路径
function normalizeFsPath(input){
    if(!input) return input;
    var raw = String(input);
    try{
        // 处理 file:// URL
        if(/^file:/i.test(raw)){
            var u = new URL(raw);
            var pathname = u.pathname || '';
            // Windows: /C:/path -> C:/path
            if(process.platform === 'win32' && /^\/[A-Za-z]:\//.test(pathname)){
                pathname = pathname.replace(/^\/([A-Za-z]:\/)/, '$1');
            }
            // 解码并使用系统分隔符
            return pathUtil.normalize(decodeURIComponent(pathname.replace(/\//g, pathUtil.sep)));
        }
    }catch(e){
        // 如果 URL 解析失败，继续走后续处理
    }
    // 处理 Windows 的 /C:/path 形式
    if(process.platform === 'win32' && /^\/[A-Za-z]:\//.test(raw)){
        raw = raw.replace(/^\/([A-Za-z]:\/)/, '$1');
    }
    // 将反斜杠转成系统分隔符并标准化
    return pathUtil.normalize(raw.replace(/[\\/]/g, pathUtil.sep));
}

exports.mv = function(filePath, point){
    filePath = normalizeFsPath(decodeURIComponent(filePath));
    var newPath = pathUtil.resolve(pathUtil.dirname(filePath), point.id + ".jpg");
    fs.renameSync(filePath, newPath);
}

exports.cp = function(file, target) {
    file = normalizeFsPath(decodeURIComponent(file));
    target = normalizeFsPath(decodeURIComponent(target));
    console.log(file, target);
    if(!target) return;
    if(fs.existsSync(file)){
        console.log('mv:', file, target);
        if(isDir(target)){
            var name = pathUtil.basename(file);
            fs.writeFileSync(pathUtil.resolve(target, name), fs.readFileSync(file));
        }else{
            var dir = pathUtil.dirname(target);
            if(!fs.existsSync(dir)){
                mkdirp.sync(dir);
            }
            if(!fs.existsSync(target)){
                //fs.writeFileSync(target, fs.readFileSync(file));
                fs.renameSync(file, target);
            }else{
                var $$ = getBowlder();
                if ($$ && $$.alert) {
                    $$.alert("重命名失败：" + target + "已存在");
                } else {
                    console.error("重命名失败：" + target + "已存在");
                }
            }
        }
        return true;
    }
}

exports.initDir = function(currentDir){
    window.recentList[0].imageDir = currentDir;
    window.recentList.save();
    exports.readVehicle(currentDir);
}

exports.readVehicle = function(dir){
    var $$ = getBowlder();
    if (!$$ || !$$.Promise) {
        // 如果 bowlder 未加载，返回一个简单的 Promise
        return Promise.resolve(window.vehicleData || {});
    }
    return $$.Promise(function(resolve){
        exports.localRead(dir, function(data){
            window.vehicleData = data;
            resolve(window.vehicleData);
        }, function(){
            window.vehicleData = {};
            resolve(window.vehicleData);
        });
    });
}

exports.saveVehicle = function(dir){   //保存data.js
    if(!dir || !fs.existsSync(dir)) return;
    var vehicleData = window.vehicleData || (window.vehicleData = {});
    vehicleData.modifytime = +new Date;
    if(!vehicleData.creator){
        vehicleData.creator = window.appInfo ? window.appInfo.user : "匿名";
    }
    if(!vehicleData.createtime){
        vehicleData.createtime = +new Date;
    }
    var current = window.recentList[0];
    vehicleData.name = current.name;
    vehicleData.id = current.id;
    exports.localSave(dir, vehicleData);
};

exports.localSave = function(file, data){   //本地存储
    if(isDir(file)){
        file = pathUtil.resolve(file, "data.js");
    }
    console.log('save', file, data);
    fs.writeFileSync(file, "exports.data=" + JSON.stringify(data), null, '    ');
};

exports.localRead = function(file, callback, callback2){   //本地读取(Sync)
    if(isDir(file)){
        file = pathUtil.resolve(file, "data.js");
    }
    if(fs.existsSync(file)){
        delete require.cache[require.resolve(file)]; //清除缓存
        var json = require(file);
        var data = json.data;
        if(data && typeof callback == 'function'){
            callback(data);
            return;
        }
    }
    if(typeof callback2 == 'function'){
        callback2();
    }
};

exports.lsr = function(root, reg){
    var dir, _dir, list = [], dirs = [''];
    while(typeof(_dir = dirs.pop()) != 'undefined'){
        dir = root + _dir;
        if(isDir(dir)){
            fs.readdirSync(dir).forEach(function(_file){
                if(_file.substr(0,1) == '.' || _file == '_backup'){
                    return;
                }
                var file = _dir + '/' + _file;
                if(!fs.statSync(root + file).isFile()){
                    dirs.push(file);
                    _file += '/';
                }
                if(!reg || (typeof(reg) == 'string' ? (_file == reg) : reg.test(_file))){
                    list.push(file);
                }
            });
        }
    }
    return list;
}

exports.exists = function(photo){
    return photo && fs.existsSync(photo.path);
}
